<template>
	<view>
		<uni-section title="选择" type="line">
			<view class="example-body">
				<uni-datetime-picker v-model="rangeDate" type="daterange" @change="handleDateChange" :clear-icon="false"
					:disabled-date="disabledDate" />
			</view>
			<uni-data-select v-model="selectedWeekday" :localdata="weekdays" @change="fetchData" :clear="true"
				placeholder="请选择周几" />
		</uni-section>
		<div ref="chartContainer" class="chart-container"></div>
	</view>
</template>

<script>
	import {
		mealRecords
	} from '@/api/order/ordering.js';
	import {
		init
	} from 'echarts/core';
	import {
		PieChart
	} from 'echarts/charts';
	import {
		TitleComponent,
		TooltipComponent,
		LegendComponent
	} from 'echarts/components';
	import {
		CanvasRenderer
	} from 'echarts/renderers';
	import {
		use
	} from 'echarts/core';

	// 注册
	use([PieChart, TitleComponent, TooltipComponent, LegendComponent, CanvasRenderer]);


	export default {
		data() {
			return {
				rangeDate: this.getCurrentWeekRange(),
				selectedWeekday: '',
				weekdays: [{
						text: '周一',
						value: '周一'
					},
					{
						text: '周二',
						value: '周二'
					},
					{
						text: '周三',
						value: '周三'
					},
					{
						text: '周四',
						value: '周四'
					},
					{
						text: '周五',
						value: '周五'
					}
				],
				chart: null
			};
		},
		mounted() {
			this.$nextTick(() => {
				setTimeout(() => {
					this.initChart();
					this.fetchData();
				}, 50); // 稍微等一下DOM渲染完成
			});
		},
		methods: {
			// 初始化图表
			initChart() {
				this.chart = init(this.$refs.chartContainer); // 用 init，而不是 echarts.init
			},

			// 获取当前周范围
			getCurrentWeekRange() {
				const today = new Date();
				const day = today.getDay() || 7;
				const monday = new Date(today);
				monday.setDate(today.getDate() - day + 1);

				const friday = new Date(monday);
				friday.setDate(monday.getDate() + 4);

				return [this.formatDate(monday), this.formatDate(friday)];
			},

			// 日期格式化
			formatDate(date) {
				return date.toISOString().split('T')[0];
			},

			// 处理日期变化
			handleDateChange(dates) {
				const [start, end] = dates.map(d => new Date(d));
				const adjustedRange = this.adjustToWeekRange(start, end);

				this.rangeDate = []; // 先清空，让组件感知变化
				this.$nextTick(() => {
					this.rangeDate = adjustedRange.map(this.formatDate); // 再赋值
					this.fetchData(); // 再拉数据
				});
			},

			// 调整为整周范围
			adjustToWeekRange(start, end) {
				const monday = new Date(start);
				monday.setDate(start.getDate() - (start.getDay() || 7) + 1);

				const friday = new Date(monday);
				friday.setDate(monday.getDate() + 4);

				return [monday, friday];
			},

			// 获取周次
			getWeekNumber(date) {
				const d = new Date(date);
				d.setHours(0, 0, 0, 0);
				d.setDate(d.getDate() + 4 - (d.getDay() || 7));
				const yearStart = new Date(d.getFullYear(), 0, 1);
				return Math.ceil(((d - yearStart) / 86400000 + 1) / 7);
			},

			// 获取数据
			async fetchData() {
				const params = {
					startDate: this.rangeDate[0],
					endDate: this.rangeDate[1],
					weekday: this.selectedWeekday
				};
				try {
					const res = await mealRecords(params);
					this.updateChart(res.data);
				} catch (error) {
					console.error('数据获取失败:', error);
				}
			},

			// 更新图表
			updateChart(data) {
				const option = {
					tooltip: {
						trigger: 'item'
					},
					series: [{
							type: 'pie',
							center: ['50%', '50%'],
							label: {
								formatter: '{b}',
								position: 'outside',
								fontSize: 12,
								overflow: 'break',
								show: true
							},
							labelLine: {
								show: true
							},
							data: this.selectedWeekday ? this.formatOuterDetailData(data) : this.formatOuterData(
								data)
						},
						{
							type: 'pie',
							center: ['50%', '50%'],
							label: {
								formatter: '{c}',
								position: 'inside',
								fontSize: 14,
								fontWeight: 'bold',
								show: true
							},
							labelLine: {
								show: false
							},
							data: this.selectedWeekday ? this.formatInnerDetailData(data) : this.formatInnerData(
								data)
						}
					]
				};
				this.chart.setOption(option);
			},
			// 外圈用的（有名字）
			formatOuterData(data) {
				const weekdaysOrder = ['周一', '周二', '周三', '周四', '周五'];
				const summary = data.reduce((acc, cur) => {
					acc[cur.weekday] = (acc[cur.weekday] || 0) + cur.totalQuantity;
					return acc;
				}, {});

				return weekdaysOrder.map(weekday => ({
					name: weekday,
					value: summary[weekday] || 0
				}));
			},

			// 详情外圈（有周几筛选）
			formatOuterDetailData(data) {
				return data.map(item => ({
					name: `${item.mealType} - ${item.weeklyRemark}`,
					value: item.totalQuantity
				}));
			},

			// ✅ 内圈用的（只要 value）
			formatInnerData(data) {
				const weekdaysOrder = ['周一', '周二', '周三', '周四', '周五'];
				const summary = data.reduce((acc, cur) => {
					acc[cur.weekday] = (acc[cur.weekday] || 0) + cur.totalQuantity;
					return acc;
				}, {});

				return weekdaysOrder.map(weekday => ({
					value: summary[weekday] || 0
				}));
			},

			// 详情内圈（有周几筛选）
			formatInnerDetailData(data) {
				return data.map(item => ({
					value: item.totalQuantity
				}));
			},

			// 禁用非工作日选择
			disabledDate(date) {
				const day = new Date(date).getDay();
				return day === 0 || day === 6; // 禁用周末
			}
		}
	};
</script>

<style lang="scss">
	.chart-container {
		width: 100%;
		height: 400px;
		box-sizing: border-box;
		padding: 0;
	}

	.example-body {
		padding: 10px;
		background: #fff;
		margin-bottom: 10px;
	}
</style>